<template>
  <PageContainer>
    <div class="login-wrapper">
      <van-form class="form-container" @submit="onSubmit">
        <van-cell-group inset>
          <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]" />
          <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]" />
        </van-cell-group>
        <div style="margin: 2em;">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, unref } from 'vue';
import { useRouter } from 'vue-router';
import { showLoadingToast, showFailToast, closeToast } from 'vant';
import PageContainer from '@/components/PageContainer.vue';
import loginApi from '@/api/login';
import { fc } from 'flutter-core';

const router = useRouter();

const username = ref<string>('');
const password = ref<string>('');

// 提交登录
const onSubmit = async (): Promise<void> => {
  const loginform = {
    username: unref(username),
    password: unref(password),
  }
  // 登录中
  showLoadingToast({
    message: '登录中...',
    forbidClick: true,
    duration: 0,
  });

  loginApi.login(loginform).then((res) => {
    // 记录token
    const token: string = res.data.token;
    sessionStorage.setItem('token', token);
    closeToast();
    router.replace('/home');
  }).catch((err) => {
    showFailToast(err.response.data.message);
  })
}

</script>

<style scoped>
.login-wrapper {
  font-size: 14px;
  padding: 2em;
  height: calc(100vh - 4em);
}

.form-container {
  margin-top: 20vh;
}
</style>
